<template>
	<div
		style="
			display: flex;
			flex-direction: column;
			justify-content: center;
			position: relative;
		"
		:style="{ margin: marginTop, width: uploadWidth }"
	>
		<div style="margin-bottom: 1vh" v-if="isShow">
			<el-text tag="del">点击选取新头像</el-text>
		</div>
		<el-upload
			ref="upload"
			action="http://localhost:5000/none"
			v-model:file-list="userAvatar"
			list-type="picture-card"
			:on-success="handleAvatarSuccess"
			:before-upload="beforeAvatarUpload"
			:limit="1"
			:on-exceed="handleExceed"
			:auto-upload="false"
		>
			<el-icon><Plus /></el-icon>

			<template #file="{ file }">
				<div>
					<img
						class="el-upload-list__item-thumbnail"
						:src="file.url"
						alt=""
					/>
					<span class="el-upload-list__item-actions">
						<span
							v-if="!disabled"
							class="el-upload-list__item-delete"
							@click="handleRemove(file)"
						>
							<el-icon><Delete /></el-icon>
						</span>
					</span>
				</div>
			</template>
		</el-upload>
		<div>
			<el-text type="danger" size="small">图片必须是JPG格式</el-text>
		</div>
		<div>
			<el-text type="danger" size="small"
				>选取的图片请不要超过5MB</el-text
			>
		</div>
		<el-row :style="{ marginTop: btnMarginTop }">
			<el-col :span="24">
				<el-button
					v-if="!submitState || !userAvatar[0]"
					disabled
					type="success"
					size="large"
					style="width: 100%"
					@click="submitAvatar"
					>{{ btnText }}</el-button
				>
				<el-button
					v-else
					type="success"
					size="large"
					style="width: 100%"
					@click="submitAvatar"
					>{{ btnText }}</el-button
				>
			</el-col>
		</el-row>
		<div>
			<el-dialog
				v-model="dialogVisible"
				title="裁剪您的图片"
				center
				style="overflow: hidden"
				:style="{ height: dialogHeight, width: dialogWidth }"
			>
				<div style="width: 550px; height: 550px" v-if="dialogVisible">
					<VueCropper
						ref="cropper"
						:img="userAvatar[0].url"
						:outputType="'jpeg'"
						:autoCrop="true"
						:autoCropWidth="CropWidth"
						:autoCropHeight="CropHeight"
						:centerBox="true"
						:canScale="false"
						:canMove="false"
						:fixed="fixed"
					></VueCropper>
				</div>
				<template #footer>
					<div>
						<el-button
							type="primary"
							size="large"
							@click="confirmCut"
						>
							裁剪
						</el-button>
						<el-button
							@click="dialogVisible = false"
							size="large"
							type="danger"
							>取消</el-button
						>
					</div>
				</template>
			</el-dialog>
		</div>
	</div>
</template>
<script setup>
import { ref, toRefs, watch } from 'vue';
import { Delete, Plus } from '@element-plus/icons-vue';
import { genFileId } from 'element-plus';
import axios from 'axios';
import 'vue-cropper/dist/index.css';
import { VueCropper } from 'vue-cropper';
import { blog } from '../store/blog.js';
const blogStore = blog();

const props = defineProps({
	marginTop: {
		default: '7vh',
	},
	btnMarginTop: {
		default: '23vh',
	},
	isShow: {
		default: true,
	},
	dialogHeight: {
		default: '680px',
	},
	dialogWidth: {
		default: '600px',
	},
	CropHeight: {
		default: '500px',
	},
	CropWidth: {
		default: '500px',
	},
	fixed: {
		default: true,
	},
	btnText: {
		default: '上传至服务器',
	},
	uploadWidth: {
		default: 'auto',
	},
});
const {
	marginTop,
	isShow,
	dialogHeight,
	dialogWidth,
	CropHeight,
	CropWidth,
	fixed,
	btnText,
	uploadWidth,
} = toRefs(props);

const disabled = ref(false);
const imageUrl = ref('');
const upload = ref('');
const userAvatar = ref([]);
const cropper = ref(null);
let imgUrl = ref('');
let dialogVisible = ref(false);
let submitState = ref(false);

const confirmCut = () => {
	cropper.value.getCropData((data) => {
		imgUrl.value = data;
		userAvatar.value[0].url = data;
		dialogVisible.value = false;
		submitState.value = true;
	});
};

watch(userAvatar, (Val) => {
	console.log(1);
	if (Val[0] && Val[0].url) {
		dialogVisible.value = true;
	}
});

const submitAvatar = async () => {
	await upload.value.submit();
};

const handleRemove = (file) => {
	upload.value.clearFiles();
};

const beforeAvatarUpload = (rawFile) => {
	console.log(rawFile);
	if (rawFile.type !== 'image/jpeg') {
		ElMessage.error('图片必须是JPG格式');
		return false;
	} else if (rawFile.size / 1024 / 1024 > 5) {
		ElMessage.error('图片的大小必须小于5MB');
		return false;
	}
	return true;
};

const handleAvatarSuccess = async (response, uploadFile) => {
	imageUrl.value = URL.createObjectURL(uploadFile.raw);
	console.log(imageUrl.value);
	if (response.state === 'ok') {
		if (!isShow.value) {
			sessionStorage.setItem('imgUrl', imgUrl.value);
			return ElNotification({
				title: 'Success',
				message: '提交成功',
				type: 'success',
			});
		} else {
			try {
				let username = localStorage.getItem('username');
				const res = await axios({
					baseURL: 'http://localhost:5000',
					url: '/updateUserAvatar',
					method: 'post',
					data: {
						username,
						imgUrl: imgUrl.value,
					},
				});
				if (res.data.state === 'ok') {
					ElNotification({
						title: 'Success',
						message: '更换头像成功',
						type: 'success',
					});
					return location.reload();
				} else {
					ElNotification({
						title: 'Warning',
						message: '头像更换失败',
						type: 'warning',
					});
					return upload.value.clearFiles();
				}
			} catch (error) {
				console.log(error);
				ElNotification({
					title: 'Error',
					message: '服务器错误',
					type: 'error',
				});
				return location.reload();
			}
		}
	}
};

const handleExceed = (files) => {
	submitState.value = false;
	upload.value.clearFiles();
	const file = files[0];
	file.uid = genFileId();
	upload.value.handleStart(file);
};
</script>
<style scoped>
.el-id-4958-7 {
	display: flex !important;
	justify-content: center !important;
}
</style>
